package allrobots.DispensingMachineThread;

import allrobots.DispensingMachine.DMAndRobotSocket;
import allrobots.Robot.RobotsSocketMap;
import allrobots.sendMessages.RobotAndDM.SendOrder;
import t10086.Model.Messages.Message;
import t10086.Model.Messages.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class DMFinishToRobotThread implements Runnable {
    private ObjectInputStream ois;
    private ObjectOutputStream oos;
    private ObjectInputStream oisRobot;
    private ObjectOutputStream oosRobot;
    private String number; //连接的机器人序列号

    public DMFinishToRobotThread(ObjectInputStream ois, ObjectOutputStream oos, ObjectInputStream oisRobot, ObjectOutputStream oosRobot, String number) {
        this.ois = ois;
        this.oos = oos;
        this.oisRobot = oisRobot;
        this.oosRobot = oosRobot;
        this.number = number;
    }

    @Override
    public void run() {
        try {
            int flag = 0;
            while (flag == 0) {
                Object read = null;
                while (read == null) {
                    // 监听机器人的信息，当机器人发送信息的时候说明机器人到了
                    read = oisRobot.readObject();
                    System.out.println("发药机正在等待机器人到达");
                    if (read != null) {
                        Message message = (Message) read;
                        if (message.convertData(String.class).equals("react")) {
                            // 给机器人订单和药(已完成)
                            String finishOrder = DispensingMachineThread.orders.poll();
                            Message toRobotMessage = new Message(MessageType.ORDER_INFO, new SendOrder(finishOrder));
                            oosRobot.writeObject(toRobotMessage);
                            oos.flush();
                            System.out.println("机器人到达来拿药");
                            flag = 1;
                            // 新建线程处理 HTTP 请求
                            new Thread(new SendOrderSystem(finishOrder, number)).start();
                        }
                    }
                }
            }
            System.out.println("与机器人断开连接");
        } catch (Exception e) {
            System.out.println("机器人异常");
            return;
        }
    }
}
